﻿using System;
using System.Web.Mvc;
using Web.Core.Models;

namespace Web.Core.ModeBinders
{
    public class ShoppingCartModelBinder : IModelBinder
    {
       
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.Model != null)
            {
                throw new InvalidOperationException("Cannot update instances");
            }

            if (controllerContext.HttpContext.Session != null)
            {
                var cart = controllerContext.HttpContext.Session[ShoppingCart.SessionKey] as ShoppingCart;

                if (cart == null)
                {
                    cart = new ShoppingCart();

                    controllerContext.HttpContext.Session[ShoppingCart.SessionKey] = cart;
                }
                return cart;
            }
            return null;
        }
    }
}